package com.pace.netty.selector;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;
/**
 * Package: com.pace.netty.selector
 * Description： TODO
 * Author: Forest
 * Date: Created in 2021/4/7 13:11
 * Version: 0.0.1
 * Modified By: duforest
 */
public class SocketMultiplexingSingleThreadv1 {


    private ServerSocketChannel server = null;
    private Selector selector = null; //linux 多路复用器（select，poll，epoll）
    int port = 9090;

    public void initServer() {
        try {
            //fd4
            server = ServerSocketChannel.open();
            server.configureBlocking(false);
            server.bind(new InetSocketAddress(port));

            /*epoll:epoll_create，在内存开辟红黑树空间,epfd3
             *poll/select：在内存开辟一个数组空间*/
            selector = Selector.open();  //  select  poll  *epoll

            /*epoll:epoll_ctl(epfd3, ADD, fd4, EPOLLIN)  此时可能还没有触发此系统调用
             * select/poll:将fd4加入数组*/
            server.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start() {
        initServer();
        System.out.println("服务器启动了。。。。。");
        try {
            while (true) {
                Set<SelectionKey> keys = selector.keys();
                System.out.println(keys.size()+"   size");

                /*epoll:epoll_wait()
                 * 懒加载：此时调用selector.select()的时候触发了上面个说的epoll_ctl的调用
                 * 这个不影响程序执行
                 * select/poll:select(fd4) poll(fd4)*/
                while (selector.select(500) > 0) {

                    Set<SelectionKey> selectionKeys = selector.selectedKeys();
                    Iterator<SelectionKey> iter = selectionKeys.iterator();
                    while (iter.hasNext()) {
                        SelectionKey key = iter.next();

                        //epoll：从链表中移除，避免重复调用
                        //select/poll：？
                        iter.remove();
                        if (key.isAcceptable()) {
                            acceptHandler(key);
                        } else if (key.isReadable()) {
                            readHandler(key);
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void acceptHandler(SelectionKey key) {
        try {
            ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
            //fd6
            SocketChannel client = ssc.accept();
            client.configureBlocking(false);
            ByteBuffer buffer = ByteBuffer.allocate(8192);

            //epoll:epoll_ctl(fd3,ADD,fd6,POLLIN)
            client.register(selector, SelectionKey.OP_READ, buffer);
            System.out.println("-------------------------------------------");
            System.out.println("新客户端：" + client.getRemoteAddress());
            System.out.println("-------------------------------------------");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void readHandler(SelectionKey key) {
        SocketChannel client = (SocketChannel) key.channel();
        ByteBuffer buffer = (ByteBuffer) key.attachment();
        buffer.clear();
        int read = 0;
        try {
            while (true) {
                read = client.read(buffer);
                if (read > 0) {
                    buffer.flip();
                    while (buffer.hasRemaining()) {
                        client.write(buffer);
                    }
                    buffer.clear();
                } else if (read == 0) {
                    break;
                } else {
                    client.close();
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        SocketMultiplexingSingleThreadv1 service = new SocketMultiplexingSingleThreadv1();
        service.start();
    }
}
